package com.whfc.ms.api.emp.service.impl;

import com.alibaba.excel.EasyExcel;
import com.whfc.common.exception.BizException;
import com.whfc.common.face.aiot.AiotApiResult;
import com.whfc.common.face.aiot.AiotCode;
import com.whfc.common.face.aiot.AiotFaceApi;
import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.result.ListData;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.ImageUtil;
import com.whfc.common.util.RandomUtil;
import com.whfc.emp.dto.AppEmpCertDTO;
import com.whfc.emp.dto.AppEmpDTO;
import com.whfc.emp.dto.AppEmpNumDTO;
import com.whfc.emp.enums.SignImgType;
import com.whfc.emp.param.*;
import com.whfc.emp.service.AppEmpConfessService;
import com.whfc.emp.service.AppEmpRiskService;
import com.whfc.emp.service.AppEmpService;
import com.whfc.emp.service.AppTrainService;
import com.whfc.entity.dto.OssPathDTO;
import com.whfc.fuum.entity.SysUser;
import com.whfc.ms.api.emp.service.MsAppEmpService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Description 人员管理
 * @Author hw
 * @Date 2020/12/28 17:42
 * @Version 1.0
 */
@Service
public class MsAppEmpServiceImpl implements MsAppEmpService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(interfaceClass = AppEmpService.class, version = "1.0.0")
    private AppEmpService appEmpService;

    @DubboReference(interfaceClass = AppTrainService.class, version = "1.0.0")
    private AppTrainService appTrainService;

    @DubboReference(interfaceClass = AppEmpConfessService.class, version = "1.0.0")
    private AppEmpConfessService appEmpConfessService;

    @DubboReference(interfaceClass = AppEmpRiskService.class, version = "1.0.0")
    private AppEmpRiskService appEmpRiskService;

    @Autowired
    private FilePathConfig filePathConfig;

    @Autowired
    private FileHandler fileHandler;

    @Override
    public PageData<AppEmpDTO> list(AppEmpListParam request) {
        return appEmpService.list(request);
    }

    @Override
    public ListData<AppEmpDTO> list(Integer deptId, String empName) {
        List<AppEmpDTO> list = appEmpService.list(deptId, empName);
        return new ListData<>(list);
    }

    @Override
    public AppEmpNumDTO num(AppEmpListParam request) {
        return appEmpService.empNum(request);
    }

    @Override
    public OssPathDTO export(AppEmpListExportParam param) throws Exception {
        return appEmpService.export(param);
    }

    @Override
    public AppEmpDTO detail(Integer empId) {
        return appEmpService.detail(empId);
    }

    @Override
    public AppEmpDTO getEmpInfo(Integer empId) {
        return appEmpService.getEmpInfo(empId);
    }

    @Override
    public OssPathDTO getEmpQr(Integer empId) throws Exception {
        return appEmpService.getEmpQr(empId);
    }

    @Override
    public void add(AppEmpAddParam request) {
        appEmpService.add(request);
    }

    @Override
    public void edit(AppEmpEditParam request) {
        appEmpService.edit(request);
    }

    @Override
    public void del(Integer empId) {
        appEmpService.del(empId);
    }

    @Override
    public String uploadImg(String base64Str, MultipartFile file, Boolean faceFlag) throws IOException {
        String path = filePathConfig.getFilePath("emp/image", RandomUtil.getRandomFileName(), "png");
        if (file != null) {
            //文件上传
            InputStream inputStream = file.getInputStream();
            String upload = fileHandler.upload(path, inputStream);
            if (faceFlag != null && faceFlag) {
                AiotApiResult<String> result = AiotFaceApi.detect(upload, null);
                if (!AiotCode.OP_SUS_1000.getValue().equals(result.getCode())) {
                    String message = AiotCode.parseByValue(result.getCode());
                    throw new BizException(ResultEnum.FAILURE.getCode(), message);
                }
            }
            return upload;
        } else if (!StringUtils.isBlank(base64Str)) {
            if (faceFlag != null && faceFlag) {
                AiotApiResult<String> result = AiotFaceApi.detect(null, base64Str);
                if (!AiotCode.OP_SUS_1000.getValue().equals(result.getCode())) {
                    String message = AiotCode.parseByValue(result.getCode());
                    throw new BizException(ResultEnum.FAILURE.getCode(), message);
                }
            }
            //base64上传
            byte[] imageByte = ImageUtil.base64ToImage(base64Str);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageByte);
            return fileHandler.upload(path, inputStream);
        }
        throw new BizException(ResultEnum.FAILURE.getCode(), "参数错误");
    }

    @Override
    public void enter(AppEmpEnterParam request) {
        appEmpService.enter(request);
    }

    @Override
    public void outer(AppEmpOuterParam request) {
        appEmpService.outer(request);
    }

    @Override
    public void outer(AppEmpOuterBatchParam request) {
        appEmpService.outer(request.getEmpIds(),request.getDate());
    }

    @Override
    public void bind(SysUser user, AppEmpDeviceBindParam request) {
        appEmpService.bind(user.getNickname(), user.getId(), request);
    }

    @Override
    public void unbind(SysUser user, AppEmpDeviceUnbindParam request) {
        appEmpService.unbind(user.getNickname(), user.getId(), request);
    }

    @Override
    public ListData<AppEmpCertDTO> certList(Integer empId) {
        List<AppEmpCertDTO> list = appEmpService.certList(empId);
        return new ListData<>(list);
    }

    @Override
    public OssPathDTO uploadCertFile(String base64Str, MultipartFile file) throws Exception {
        OssPathDTO ossPathDTO = new OssPathDTO();
        String path = filePathConfig.getFilePath("emp/cert/img", RandomUtil.getRandomFileName(), ".png");
        if (file != null) {
            //文件上传
            InputStream inputStream = file.getInputStream();
            String upload = fileHandler.upload(path, inputStream);
            ossPathDTO.setPath(upload);
            return ossPathDTO;
        } else if (!StringUtils.isBlank(base64Str)) {
            //base64上传
            byte[] imageByte = ImageUtil.base64ToImage(base64Str);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageByte);
            String upload = fileHandler.upload(path, inputStream);
            ossPathDTO.setPath(upload);
            return ossPathDTO;
        }
        throw new BizException(ResultEnum.FAILURE.getCode(), "参数错误");
    }

    @Override
    public void delCert(Integer certId) {
        appEmpService.delCert(certId);
    }

    @Override
    public void addCert(AppEmpCertAddParam request) {
        appEmpService.addCert(request);
    }

    @Override
    public void editCert(AppEmpCertEditParam request) {
        appEmpService.editCert(request);
    }

    @Override
    public void uploadSignImg(String signImg, Integer id, String type, Integer empId) {
        if (StringUtils.isBlank(signImg)) {
            return;
        }
        SignImgType imgType = SignImgType.parseCode(type);
        if (imgType == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "图片类型错误");
        }
        //上传文件
        String fileUrl = "";
        try {
            String path = filePathConfig.getFilePath("emp/sign/img/" + type, RandomUtil.getRandomFileName(), "png");
            byte[] imageByte = ImageUtil.base64ToImage(signImg);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageByte);
            fileUrl = fileHandler.upload(path, inputStream);
        } catch (Exception e) {
            logger.warn("上传培训附件失败.");
        }
        if (StringUtils.isBlank(fileUrl)) {
            throw new BizException(ResultEnum.UNKNOWN_ERROR.getCode(), "图片上传失败.");
        }
        if (SignImgType.TRAIN_EMP.equals(imgType)) {
            //培训人员签名图片
            appTrainService.saveSignImg(id, fileUrl);
        } else if (SignImgType.CONFESS.equals(imgType)) {
            //安全交底签名图片
            appEmpConfessService.saveConfessSignImg(id, fileUrl);
        } else if (SignImgType.RISK.equals(imgType)) {
            //风险告知书签名图片
            appEmpRiskService.saveRiskSignImg(id, empId, fileUrl);
        }
    }

    @Override
    public OssPathDTO uploadImg(MultipartFile file, String module) {
        String filename = file.getOriginalFilename();
        String suffix = "png";
        if (StringUtils.isNotBlank(filename)) {
            suffix = filename.substring(filename.lastIndexOf(".") + 1);
        }
        String imgUrl = "";
        try {
            String path = filePathConfig.getFilePath("emp/" + module + "/img", RandomUtil.getRandomFileName(), suffix);
            InputStream inputStream = file.getInputStream();
            imgUrl = fileHandler.upload(path, inputStream);
        } catch (Exception e) {
            logger.warn("上传图片失败", e);
        }
        return new OssPathDTO(imgUrl);
    }

    @Override
    public void importEmp(Integer deptId, MultipartFile file) {
        List<AppEmpImportParam> list;
        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "文件名不合法");
        }
        String[] split = filename.split("\\.");
        if (split.length < 2 || (!"xls".equals(split[1]) && !"xlsx".equals(split[1]))) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "文件不合法");
        }
        try {
            list = EasyExcel.read(file.getInputStream()).head(AppEmpImportParam.class).
                    sheet().
                    headRowNumber(1).
                    doReadSync();
        } catch (Exception e) {
            logger.warn("导入人员失败", e);
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "导入人员失败");
        }
        if (list == null || list.isEmpty()) {
            return;
        }
        appEmpService.importEmp(deptId, list);
    }

    @Override
    public void delList(List<Integer> empIdList){
        appEmpService.delList(empIdList);
    }

    @Override
    public boolean checkVideoHelmet(SysUser user, String sn) {
        return appEmpService.checkVideoHelmet(sn);
    }

    @Override
    public void syncWorker(AppEmpEditParam request) {
         appEmpService.syncWorker(request);
    }

    @Override
    public List<AppEmpDTO> getLeaderList(Integer deptId, String keyword) {
        return appEmpService.getLeaderList(deptId, keyword);
    }
}
